﻿using System;
using System.Collections;
using System.Collections.Generic;

using UnityEngine;


public enum ECharModel
{
	none,
	Assassin,
	Sorcerer,
	Templar,
	Dukakidigger,
	Dukakiminer,
	Dukakipatrol,
	Haskin,
	Kuntura,
	Paruka,
	Takata,
	Raksha,//boss
	Cleric,
	Spiritmaster,
	Ranger,
	Rudra,//boss
	ManduriB,
	ShellizardNamed,
	Agrint,
	Basilisk,
	Cherubim1,
	Cherubim2,
	Ghost,
	Gladiator,
	KrallShamanHT,
	LycanRanger,
	Spakle,
	Sprigg,
	Worm,
	Chanter,
	nagamage_named,
}

public class ProjectileRes
{
	public GameObject projectile;
	public GameObject hit;
}

public class BattleResManager : MonoBehaviour {

	private static BattleResManager instance;
	
	public static BattleResManager Instance{
		get{
			return instance;
		}
	}	
	
	void Awake()
	{
		instance = this;
	}

	public static Dictionary<ECharModel, int> modelMapForViewer = new Dictionary<ECharModel, int>
	{
		{ECharModel.Templar , 7},
		{ECharModel.Assassin , 13},
		{ECharModel.Sorcerer , 22},
		{ECharModel.Cleric , 38},
		{ECharModel.Spiritmaster , 28},

		{ECharModel.Dukakidigger , 40},
		{ECharModel.Dukakipatrol , 41},
		{ECharModel.Dukakiminer , 42},
		{ECharModel.Kuntura , 43},
		
		{ECharModel.Takata , 44},
		{ECharModel.Paruka , 45},
		{ECharModel.Haskin , 46},
		
		{ECharModel.Raksha , 47},
		{ECharModel.Rudra , 48},
		
	};

	public static Dictionary<int, GameObject> pawnPrefabDic = new Dictionary<int, GameObject>();
	public static Dictionary<string, GameObject> weaponPrefabDic = new Dictionary<string, GameObject>();

	public Dictionary<string, ProjectileRes> projectileResDic = new Dictionary<string, ProjectileRes>();
	public Dictionary<string, GameObject> ultimateHitPrefabDic = new Dictionary<string, GameObject>();
	public GameObject ultimateReadyPrefab;
	GameObject ultimageReadyFX;

    public static GameObject CreatePawn(int modelID, bool _isPlayer)
    {
        return CreatePawn(0, modelID, _isPlayer);
    }

	public static GameObject CreatePawn(int _no, int modelID, bool _isPlayer)
	{
		GameObject go = null;
        if(BattleViewer.Instance!=null) {
			GameObject prefabGo = BattleViewer.Instance.GetModelPrefab(modelID, _isPlayer);
			go = Instantiate( prefabGo ) as GameObject;
		}
		else {
			if(!pawnPrefabDic.ContainsKey(modelID)) {
				string prefabPath = "Prefab/Battle/Character/" + GameData.Inst.ModelDefineDic[modelID];
				GameObject prefabGo = Resources.Load (prefabPath) as GameObject;
				if(prefabGo==null)
					Debug.LogError(modelID+"   prefab go null  "+prefabPath);
				pawnPrefabDic.Add (modelID,  prefabGo );
			}

			if(_isPlayer ) {
				go = ResourceManager.Inst.GetChoiceMemberGo(_no);
				if(go==null) {
					go = Instantiate( pawnPrefabDic[modelID] ) as GameObject;
					ResourceManager.Inst.AddChoiceMemberGo(_no, go);
				}
			}
			else
				go = Instantiate( pawnPrefabDic[modelID] ) as GameObject;
		}
		return go;

	}

	public static Dictionary<int, GameObject> massPawnPrefabDic = new Dictionary<int, GameObject>();
	public static GameObject CreateMassPawn(int modelId)
	{
		if(!massPawnPrefabDic.ContainsKey(modelId)) {
			string modelName = GameData.Inst.ModelDefineDic[modelId];
			modelName += "_Low";
			GameObject prefabGo = Resources.Load ("Prefab/Battle/Character/" + modelName) as GameObject;
			if(prefabGo==null) {
				Debug.LogError("prefab null  "+modelName);
				return null;
			}
			massPawnPrefabDic.Add (modelId,  prefabGo );
		}
		GameObject go = Instantiate( massPawnPrefabDic[modelId] ) as GameObject;
		go.name = massPawnPrefabDic[modelId].name;
		return go;
	}

	public static bool IsBossClass(ECharModel charModel)
	{
		if(charModel== ECharModel.Raksha || charModel== ECharModel.Rudra || charModel== ECharModel.ManduriB || charModel== ECharModel.ShellizardNamed || charModel== ECharModel.Sprigg)
			return true;
		return false;
	}

	public void LoadProjectile(string charModel, ProjectileInfo projectileInfo)
	{
		if(!projectileResDic.ContainsKey(charModel) ) {
			ProjectileRes projectileRes = new ProjectileRes();
			string prefabPath = "Prefab/Battle/FX/";
			string fullpath = "";
			if(string.IsNullOrEmpty(charModel) || string.Equals(charModel, ECharModel.none.ToString())) {
				Debug.LogError("charmodel none");
			}
			if(projectileInfo.resRoot.IsNullOrEmpty())
				fullpath = string.Format("{0}{1}/{2}",prefabPath, charModel, projectileInfo.projectileResPath);
			else
				fullpath = string.Format("{0}{1}/{2}",prefabPath, projectileInfo.resRoot, projectileInfo.projectileResPath);
//			Debug.Log("projectile res path = "+fullpath);
			projectileRes.projectile = Resources.Load ( fullpath ) as GameObject;
			projectileRes.projectile.SetActive(false);
			if(projectileInfo.resRoot.IsNullOrEmpty())
				projectileRes.hit = Resources.Load (string.Format("{0}{1}/{2}",prefabPath, charModel, projectileInfo.projectileHitResPath) ) as GameObject;
			else
				projectileRes.hit = Resources.Load (string.Format("{0}{1}/{2}",prefabPath, projectileInfo.resRoot, projectileInfo.projectileHitResPath) ) as GameObject;
			projectileRes.hit.SetActive(false);
			projectileResDic.Add ( charModel, projectileRes);
		}
	}

	public static ECharModel FindCharModel(int modelID)
	{
		string modelName = GameData.Inst.ModelDefineDic[modelID];

		return FindCharModel(modelName);
	}

	public static ECharModel FindCharModel(string modelName)
	{
		string [] charNames = Enum.GetNames(typeof(ECharModel));
		
		int i=0;
		int nModel=0;
		foreach( string charName in charNames)
		{
			if(modelName.StartsWith(charName) )
			{
				nModel = i;
				break;
			}
			i++;
		}
		return (ECharModel)nModel;
	}

	public static GameObject [] AttachWeaponLow(GameObject _parent, BattleCharInfo charInfo, int [] itemModelId, bool bForceCreate)
	{
		return DoAttachWeapon(_parent, charInfo, itemModelId, bForceCreate, true);
	}

	public static GameObject [] AttachWeapon(GameObject _parent, BattleCharInfo charInfo, int [] itemModelId, bool bForceCreate)
	{
		return DoAttachWeapon(_parent, charInfo, itemModelId, bForceCreate, false);
	}

	public static GameObject [] DoAttachWeapon(GameObject _parent, BattleCharInfo charInfo, int [] itemModelId, bool bForceCreate, bool isLowModel)
	{
		GameObject [] weaponGo = new GameObject[2];
		string [] modelNames = { charInfo.R_Weapon_Model, charInfo.L_Weapon_Model }; //default weapon name
		string [] attachNames = { charInfo.R_Weapon_AttachName, charInfo.L_Weapon_AttachName };
          
		for(int i=0; i<2; i++)
        {
			string modelName = modelNames[i];
            
			if (string.IsNullOrEmpty(modelName))
				continue;
			if(itemModelId!=null && itemModelId[i]!=0) {
				modelName = GameData.Inst.ItemDefineDic[ itemModelId[i] ];
				Debug.LogError(i+"  AttachWeapon  id="+itemModelId[i]+"  "+modelName);
			}
			if(isLowModel)
				modelName += "_Low";

			string attachName = attachNames[i];

			if(!weaponPrefabDic.ContainsKey(modelName) ) {
				GameObject weaponPrefab = Resources.Load ("Prefab/Battle/Weapon/" + modelName) as GameObject;
				if(weaponPrefab!=null)
					weaponPrefabDic.Add ( modelName, weaponPrefab );
				else
					Debug.LogError("weaponPrefab null  "+modelName);
			}
			
            GameObject go=null;
			Transform child = _parent.transform.FindChild(attachName);
			
            if(child==null) {
				MassiveBattle.Controller.BaseController unitControl = _parent.GetComponent<MassiveBattle.Controller.BaseController>();
				if(unitControl!=null)
					Debug.LogError(unitControl.ClassName+ "  AttachWeapon  bone not found  :  "+attachName);
				else {
					PawnManifest mani = _parent.GetComponent<PawnManifest>();
					if(mani!=null)
						Debug.LogError(mani.parentPawn.myModelStr+ "  AttachWeapon  bone not found  :  "+attachName);
					else
						Debug.LogError("AttachWeapon  bone not found  :  "+attachName);
				}
				continue;
			}
			else {
				MeshRenderer [] weaponsAttached = child.GetComponentsInChildren<MeshRenderer>();
				if(bForceCreate || weaponsAttached.Length==0)
					go = child.Find(modelName) == null ? CreateWeapon(modelName, child) : child.Find(modelName).gameObject;
				else {
					bool bFoundModel = false;
					foreach(MeshRenderer attached in weaponsAttached) {
						if(attached.gameObject.name == modelName) {
							go = attached.gameObject;
							//go.SetActive(true);
							bFoundModel=true;
							break;
						}
						else {
							//attached.gameObject.SetActive(false);
							Destroy(attached.gameObject);
						}
					}
					if(!bFoundModel)
						go = CreateWeapon(modelName, child);
				}
			}
			
            
			weaponGo[i] = go;
		}

		return weaponGo;
	}

	static GameObject CreateWeapon(string modelName, Transform _parent)
	{
		if(!weaponPrefabDic.ContainsKey(modelName) )
			return null;
		GameObject go = Instantiate( weaponPrefabDic[modelName] ) as GameObject;
		go.name = modelName;
		go.transform.parent = _parent;
		go.transform.localPosition = Vector3.zero;
		go.transform.localRotation = Quaternion.identity;
		go.transform.localScale = Vector3.one;
		return go;
	}

	public void ShowUltimateReady(Transform _parent)
	{
		ClearUltimateReady();
		if(ultimateReadyPrefab==null)
			ultimateReadyPrefab = Resources.Load ("Prefab/Battle/FX/FX_PC_UltimateReady") as GameObject;
		GameObject go = Instantiate( ultimateReadyPrefab) as GameObject;
		go.transform.parent = _parent;
		go.name = "ultimateready";
		Debug.LogError("ShowUltimateReady");
		BattleUtil.ClearTransformLocal(go.transform);
		go.SetActive(true);
		ultimageReadyFX = go;
	}

	public void ClearUltimateReady()
	{
		if(ultimageReadyFX!=null) {
			Destroy(ultimageReadyFX);
			ultimageReadyFX=null;
		}
	}

	public void ShowUltimateHit(string attackerModel, Transform _parent)
	{
		if( !ultimateHitPrefabDic.ContainsKey( attackerModel) )
			ultimateHitPrefabDic.Add ( attackerModel, Resources.Load ("Prefab/Battle/FX/" + attackerModel + "/Ultimate_hit" ) as GameObject );
		if(ultimateHitPrefabDic[attackerModel]==null)
			return;
		GameObject go = Instantiate( ultimateHitPrefabDic[attackerModel] ) as GameObject;
		go.transform.parent = _parent;
		BattleUtil.ClearTransformLocal(go.transform);
		go.SetActive(true);
		Destroy(go, 2.0f);
	}

	public static bool IsBossModel(ECharModel _charModel)
	{
		if(_charModel== ECharModel.Raksha || _charModel== ECharModel.ManduriB || _charModel== ECharModel.Rudra || _charModel== ECharModel.ShellizardNamed)
			return true;
		return false;
	}

	public static bool IsHealerModel(ECharModel _charModel)
	{
		if(_charModel== ECharModel.Cleric || _charModel== ECharModel.Chanter)
			return true;
		return false;
	}
}
